<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>

<div class="fieldBox col_100">
    <div class="sqPanel">
        <div>
            <div id="ligergrid_def_fee_sett" class="sq-grid"></div>
        </div>
    </div>
</div>
<!-- 添加结清费用项 -->
<div class="fieldBox col_100">
    <div class="sqPanel">
        <div class="sqPanel_head inL" style="margin:0 0 30px 0">
            <div class="btnsBox inLC">
                <span id="addBtn" class="sq-button sq-button-round operation"><!-- <i class="sqBtnIco_3"></i> -->添加</span>
                <span id="delBtn" class="sq-button sq-button-round operation"><!-- <i class="sqBtnIco_7"></i> -->删除</span>
            </div>
        </div>
        <div>
            <div id="ligergrid_fee_sett" class="sq-grid"></div>
        </div>
    </div>
</div>
<div class="fieldBox col_100">
    <div class="label">应收结清款</div>
    <input style="display: none" id="baseSettAmt" value="${pay.totalSettAmt}">
    <div class="field">
        <span id="totalSettAmt">${pay.totalSettAmt}</span>
    </div>
</div>
<div class="btnsBox">
    <span id="saveBtnSettFee" style="margin:10px 0 0 0" class="sq-button sq-button-round operation"><i class="sqBtnIco_10"></i>保存</span>
</div>

<script type="text/javascript">
    var basePath = '<%=path%>';
    var taskDefKey = '${taskDefKey}';
    var procInstId = '${procInstId}';
    var model = '${model}';
    var isDetail = '${isDetail}';
    var wsPaySchId = '${wsPaySchId}' == ''?'${pay.wsPaySchId}' : '${wsPaySchId}';
    var feeSettGrid, defFeeSettGrid;
    var settAddFeeAmt = 0; //结清添加的费用项
    var settFeeTypCdListJSON = [];
    <c:if test="${not empty settFeeTypCdListJSON}">
    settFeeTypCdListJSON = ${settFeeTypCdListJSON};
    </c:if>

    $(function () {
        if (isDetail == '1') {
            $(".operation").hide();
        }
        prjQuatPrpsDefFeeSettGrid();
        prjQuatPrpsfeeSettGrid();
    });

    // 新增费用项，页面操作，无后台交互
    $("#addBtn").click(function (event) {
        feeSettGrid.addRow({
            id: '',
            feeTypCd: '',
            feeAmt: ''
        });
    });
    // 删除费用项，有后台交互
    $("#delBtn").click(function (event) {
        if (!checkOnlineSettStatus()) {
            return;
        }
        var selectedRows = feeSettGrid.getSelectedRows();
        if (selectedRows.length < 1) {
            $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_SELECT_ONLY_A_ROW, SQ_type: "warring"});
            return;
        }
        var _ids = [];
        $.ligerDialog.confirm(LogUtils.LOG_CMM_DELETE_CONFIRM, function (flag) {
            if (flag == false) return;
            for (var index in selectedRows) {
                if (selectedRows[index].isSysDef) {
                    if (selectedRows[index].isSysDef == CommonConstant.C_YN_Y) {
                        $.ligerDialog.SQalert({content: "不允许删除默认的结清费用项", SQ_type: "warring"});
                        return;
                    }
                }
                if (selectedRows[index].id) {
                    _ids.push(selectedRows[index].id);
                }
            }
            if (!_ids || _ids.length == 0) {
                feeSettGrid.removeRange(feeSettGrid.getSelectedRows());
                modifySettValue();
                top.$.ligerDialog.SQalert({content: "删除成功！", SQ_type: "success"});
                return;
            }
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: {paySchId: wsPaySchId, ids: JSON.stringify(_ids)},
                url: basePath + '/project/prjPrdPaySchD/removeSettFee.do',
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        defFeeSettGrid.reload();
                        feeSettGrid.reload();
                        $("#baseSettAmt").val(msg.data);
                        $("#totalSettAmt").text(msg.data);
                        top.$.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                    } else {
                        top.$.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                    }
                }
            });
        });
    });

    // 保存
    $("#saveBtnSettFee").click(function (event) {
        $.ligerDialog.confirm("确定要保存吗？", function (flag) {
            if(!flag) return;
            if (!checkOnlineSettStatus()) {
                return;
            }
            //验证是否有重复的费用项
            var settDetailListData = feeSettGrid.getData();
            var settDetailListDataArr = [];
            var result = new Array();
            if (settDetailListData) {
                for (var i = 0; i < settDetailListData.length; i++) {
                    var obj = settDetailListData[i];
                    //费用金额不对修改
                    if (obj.feeClsCd == "FIN10001" && obj.paidUpAmt > 0) {
                        continue;
                    }
                    if (!obj.capFlow) {
                        obj.capFlow = obj.codeAttr1;
                    }
                    settDetailListDataArr.push(obj);
                    if (!obj.isSysDef || obj.isSysDef == CommonConstant.C_YN_N) {
                        var idx = obj.feeTypCd;
                        if (result[idx]) {
                            result[idx] = parseInt(result[idx]) + 1;
                        } else {
                            result[idx] = 1;
                        }
                    }
                }
            }
            var extContAmt = $("#extContAmt").val();
            var settPct = $("#settPct").val();
            //var reduAmt = $("#reduAmt").val();
            var reduTotalAmt = $("#reduTotalAmt").val();
            var data = {};
            var prjId = '${prj.id}';
            data.paySchId = wsPaySchId;
            data.totalSettAmt = $("#totalSettAmt").text();
            data.reduStartLsPd = $("#reduStartLsPd").val();
            data["settFeeList"] = JSON.stringify(settDetailListDataArr);
            data["settFlag"] = "pre";
            data["discountAmt"] = '${pay.discountAmt}';
            data["breachAmt"] = '${pay.breachAmt}';
            data["extContAmt"] = extContAmt;// 合同外优惠金额
            data["settPct"] = settPct;// 结清比例
            data["reduAmt"] = reduTotalAmt;// 优惠金额总计
            data["yzdgFlag"] = '${yzdgFlag}';
            data["prjId"] = prjId;
            var url = '<%=path%>/project/prjPrdPaySchD/addSettFee.do';
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: data,
                url: url,
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        defFeeSettGrid.reload();
                        feeSettGrid.reload();
                        $("#baseSettAmt").val(msg.data);
                        $("#totalSettAmt").text(msg.data);
                        $.ligerDialog.SQalert({content: "保存成功！", SQ_type: "success"});
                    } else {
                        $.ligerDialog.SQalert({content: "保存失败！", SQ_type: "error"});
                        location.reload();
                    }
                }
            });
        });
    });

    // 重新计算结清款
    function modifySettValue() {
        var total = 0;
        var rows = feeSettGrid.rows;
        for (var i = 0; i < rows.length; i++) {
            var feeAmt = rows[i].feeAmt;
            if (typeof feeAmt == "number") {
                var capFlow = rows[i].codeAttr1 == undefined ? rows[i].capFlow : rows[i].codeAttr1;
                if (capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                    total -= feeAmt;
                }
                if (capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_IN) {
                    total += feeAmt;
                }
            }
        }
        var settAmt = $("#baseSettAmt").val();
        var totalSetAmt = NumberUtils.add(NumberUtils.sub(settAmt, settAddFeeAmt), total);
        $("#totalSettAmt").text(totalSetAmt);
    }

    // 加载结清费用项
    function prjQuatPrpsfeeSettGrid() {
        var params = {};
        params.paySchId = wsPaySchId;
        params.prjId = '${dtl.prjId}';
        feeSettGrid = $("#ligergrid_fee_sett").ligerGrid({
            method: 'get',
            parms: params,
            url: basePath + '/project/prjPrdPaySchD/getPrjPrdPaySchSettFeeList.do',
            columns: [
                {display: '费用类型', name: 'feeTypCd', minWidth: 80,
                    editor: {
                        type: 'select',
                        data: settFeeTypCdListJSON,
                        valueField: 'code',
                        textField: 'codeNm'
                    },
                    valueField: 'feeTypCd',
                    textField: 'feeTypCdNm',
                    render: function (item) {
                        return item.feeTypCdNm;
                    }
                },
                {display: '金额', name: 'feeAmt', minWidth: 80, type: 'numberbox',
                    editor: { type: 'number', precision: 2, toFix: true,
                        onToFix: function () {
                            top.$.ligerDialog.SQalert({SQ_type: "warning", content: "小数点后面最多2小数！"});
                        }
                    },
                    render: function (item) {
                        if (StringUtils.isEmpty(item.feeAmt)) {
                            return;
                        }
                        var amt = renderAmt(null, null, item.feeAmt);
                        if (item.capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT
                            || item.codeAttr1 == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                            amt = "<span style='color:red'>-" + amt + "</span>";
                        }
                        return amt;
                    }
                },
                { display: '未核销金额', name: 'arAmt', minWidth: 80, type: 'currency',
                    render: function (item) {
                        if (StringUtils.isEmpty(item.arAmt)) {
                            return;
                        }
                        var amt = renderAmt(null, null, item.arAmt/100);
                        return amt;
                    }
                }
            ],
            onSuccess: function (rowDatas, grid) {
                var data = rowDatas.rows;
                settAddFeeAmt = 0;
                if (data != null) {
                    for (var i = 0; i < data.length; i++) {
                        var feeAmt = data[i].feeAmt;
                        if (data[i].capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                            feeAmt = -1 * feeAmt;
                        }
                        settAddFeeAmt += feeAmt;
                    }
                }
            },
            onBeforeSubmitEdit: function (e) {//重新赋值,要不然选中后离开会把key显示在前端
                //var colNanme = e.column.columnname;
                if (e.selected && e.column.columnname == "feeTypCd") {
                    e.record.feeTypCdId = e.value;
                    e.value = e.selected[e.column.editor.textField];
                    e.record.codeAttr1 = e.selected.codeAttr1;
                }

                if (e.record.isSysDef == 1) {
                    e.column.editor.readonly = true;
                } else {
                    e.column.editor.readonly = false;
                }
            },
            onAfterEdit: function (e) {
                var colNanme = e.column.columnname;
                if (e.selected && e.column.columnname == "feeTypCd") {
                    e.record.codeAttr1 = e.selected.codeAttr1;
                    e.record.feeTypCd = e.selected.code;
                }
                if (e.record.isSysDef == 1 && colNanme != "feeAmt") {
                    e.column.editor.readonly = true;
                } else {
                    e.column.editor.readonly = false;
                }
                feeSettGrid.updateCell('feeAmt', e.record.feeAmt, e.record);
                feeSettGrid.updateCell('capFlow', e.record.codeAttr1, e.record);
                if (StringUtils.isNotEmpty(e.record.feeAmt)) {
                    modifySettValue();
                }
            },
            //费用金额不对修改
            onBeforeEdit: function (e) {
                if (e.record.id == null) {
                    //可修改
                    e.column.editor.readonly = false;
                } else {
                    if (e.record.paidUpAmt == null || e.record.paidUpAmt == 0) {
                        //可修改
                        e.column.editor.readonly = false;
                    } else {
                        //不可修改
                        e.column.editor.readonly = true;
                    }
                }
            },
            usePager: false,
            pageSize: 100,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: 200,
            heightDiff: -2,
            enabledEdit: true,
            isScroll: false,
            checkbox: true,
            rownumbers: true,
            allowUnSelectRow: true,
            alternatingRow: true,
            usePagerOnLessPagesize: false,
        });
    }

    // 加载默认的费用项
    function prjQuatPrpsDefFeeSettGrid() {
        defFeeSettGrid = $("#ligergrid_def_fee_sett").ligerGrid({
            columns: [
                {display: '费用类型', name: 'feeTypCdNm', minWidth: 80},
                {
                    display: '金额', name: 'feeAmt', minWidth: 80, type: 'numberbox',
                    render: function (item) {
                        var amt = "<span>" + item.feeAmt + "</span>";
                        if (item.capFlow == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                            amt = "<span style='color:red'>-" + item.feeAmt + "</span>";
                        }
                        if (item.codeAttr1 == ProjectConstant.CODE_PRJ_QUAT_CASH_FLOW_OUT) {
                            amt = "<span style='color:red'>-" + item.feeAmt + "</span>";
                        }
                        return amt;
                    }
                }
            ],
            usePager: false,
            pageSize: 100,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: 180,
            heightDiff: -2,
            enabledEdit: false,
            isScroll: false,
            checkbox: true,
            rownumbers: true,
            allowUnSelectRow: true,
            alternatingRow: true,
            usePagerOnLessPagesize: false,
        });
        if (model == 'preview') {
            var defSetFeeAmtData = {
                "rows": [
                    {"feeTypCdNm": "结清优惠金额1", "feeAmt": '${pay.discountAmt1}', "capFlow": '2'},
                    {"feeTypCdNm": "结清优惠金额", "feeAmt": '${pay.discountAmt}', "capFlow": '2'},
                    {"feeTypCdNm": "违约金", "feeAmt": '${pay.breachAmt}', "capFlow": '1'}
                ],
                "total": 3
            };
            defFeeSettGrid.loadData(defSetFeeAmtData);
        } else {
            defFeeSettGrid.set({
                method: 'get',
                parms: {paySchId: wsPaySchId},
                url: basePath + '/project/prjPrdPaySchD/getPrjPrdPaySchDefSettFeeList.do'
            });
        }
    }

    // 校验狮桥在线结清申请状态是否正常
    function checkOnlineSettStatus() {
        var result = true;
        // 狮桥在线结清
        if (taskDefKey.indexOf("FLOW_00000001_063") == 0) {
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: {"paySchId": paySchId, "procInstId": procInstId, "branchKey": taskDefKey},
                url: '<%=path%>/settlement/checkStatus.do',
                async: false,
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        result = msg.data;
                    } else {
                        result = msg.data;
                        $.ligerDialog.SQalert({content: msg.info, SQ_showButtons: true, SQ_type: "error"});
                    }
                }
            });
        }
        return result;
    }



</script>